package myexchange

import grails.converters.JSON;
import myexchange.TurnService.TurnState;


class GameController {

    def scaffold = Game

	ExchangeService exchangeService
	GameService gameService
	TurnService turnService
	
    def index = {
		Game game = gameService.activeGame
		if(!game){
			redirect(action:"create")
		}

    }
	
	def listJSON = {
		println params
		def sortIndex = params.sidx ?: 'name'
		def sortOrder  = params.sord ?: 'asc'
		def maxRows = Integer.valueOf(params.rows)
		def currentPage = Integer.valueOf(params.page) ?: 1
		def rowOffset = currentPage == 1 ? 0 : (currentPage - 1) * maxRows
		def players = Player.list(sort:sortIndex, order:sortOrder, max:10, offset:rowOffset)
		def totalRows = Player.count()
		def numberOfPages = Math.ceil(totalRows / maxRows)
		def results = players?.collect{
			[
				cell: [it.nickname, it.userName, it.firstName, it.lastName, it.password],
				id: it.id
		   ]
		}
		
		def jsonData = [rows: results, page: currentPage, records: totalRows, total: numberOfPages]
		render jsonData as JSON
	}
	
	def editJSON = {
		println params
	}
	
	def create = {
		def players = Player.list()
		Game game = gameService.activeGame
		render(view:"create", model:[players:players,gameInstance:game])
	}
	
	def reloadTurnStatusPanel = {
		Turn turn = turnService.getCurrentTurn()
		Game game = gameService.getActiveGame()
		def playerActions = PlayerAction.findAllWhere([
				turn:turn,
				type:PlayerActionType.END
			])
		def players = game.players.sort{it.nickname}
		Map status = [:]
		for (Player player : players){
			status[player] = "P"
			for(PlayerAction action : playerActions){
				if(action.player.userName == player.userName){
					status[player] = "R"
				}
			}
		}
		render(template:"turnStatusPanel", model:[players:players, status:status, turn:turn])
	}

	def reloadExchangePanel = {
		def playerList = Player.list();
		def shareList = Share.list();
		def exchangeList = Exchange.list()
		def exchangeMap = [:]
		def key;
		def value;
		exchangeList.each {
				key = "${it.player.id}x${it.share.id}".toString();
				value = it.quantity;
				exchangeMap.put(key,value);
			}
		render(template:"/exchange/exchangePanel", model: [playerInstanceList:playerList, exchangeMap:exchangeMap,shareList:shareList])
    }
	
	def reloadPlayerInfo = {
		Player player = Player.get(session.user.id) 
		render(template:"/player/playerInfo", model: [player:player])
	}
	
	def reloadHistory = {
		def turnNumber = turnService.getCurrentTurn()?.number
		turnNumber = (turnNumber > 1)?turnNumber-1:1
		def historyList = History.createCriteria().list(){
				turn{
					ge("number",turnNumber)
				}	
			}
		render(template:"/game/historyPanel", model: [historyList:historyList])
	}
	
	def reloadCardHistory = {
		def cards = gameService.getActiveGame().usedCards
		if(cards.size()>6){
			cards = cards[-1..-6]
		}
		render(template:"/game/cardsHistory", model: [cardList:cards])
	}
	
	def loadActionPanel = {
		Player player = Player.get(session.user.id)
		TurnState state = turnService.getTurnState(player)
		switch (state) {
			case TurnState.NEW:
				render(template:"actionPanel", model:[state:state])
				break;
			case TurnState.STARTED:
				forward(controller:"turn",action:"startTurn")
				break;
			case TurnState.CARD:
				forward(controller:"turn",action:"selectCard")
				break;
			case TurnState.TRADING:
				forward(controller:"turn",action:"trade")
				break;
			case TurnState.READY:
				render(template:"actionPanel", model:[state:state])
				break;
			default:
				break;
		}
		
	}
}
